import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '扩展计数器',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '扩展计数器'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<int> _counterHistory = [];
  bool _isDarkMode = false;
  bool _isLoading = false;
  final TextEditingController _customValueController = TextEditingController();

  void _incrementCounter() {
    setState(() {
      _counter++;
      _counterHistory.add(_counter);
    });
  }

  void _decrementCounter() {
    setState(() {
      if (_counter > 0) {
        _counter--;
        _counterHistory.add(_counter);
      }
    });
  }

  void _resetCounter() {
    setState(() {
      _counter = 0;
      _counterHistory.add(_counter);
    });
  }

  void _showCustomValueDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('设置自定义值'),
          content: TextField(
            controller: _customValueController,
            keyboardType: TextInputType.number,
            decoration: const InputDecoration(
              labelText: '输入数值',
              border: OutlineInputBorder(),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _customValueController.clear();
              },
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                final value = int.tryParse(_customValueController.text);
                if (value != null) {
                  setState(() {
                    _counter = value;
                    _counterHistory.add(_counter);
                  });
                }
                Navigator.of(context).pop();
                _customValueController.clear();
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showHistoryDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('计数历史'),
          content: SizedBox(
            width: double.maxFinite,
            height: 300,
            child:
                _counterHistory.isEmpty
                    ? const Center(child: Text('暂无历史记录'))
                    : ListView.builder(
                      itemCount: _counterHistory.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                          leading: CircleAvatar(child: Text('${index + 1}')),
                          title: Text('计数: ${_counterHistory[index]}'),
                          subtitle: Text('第 ${index + 1} 次操作'),
                        );
                      },
                    ),
          ),
          actions: [
            TextButton(
              onPressed: () {
                setState(() {
                  _counterHistory.clear();
                });
                Navigator.of(context).pop();
              },
              child: const Text('清空历史'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('关闭'),
            ),
          ],
        );
      },
    );
  }

  void _toggleTheme() {
    setState(() {
      _isDarkMode = !_isDarkMode;
    });
  }

  Future<void> _simulateAsyncOperation() async {
    setState(() {
      _isLoading = true;
    });

    // 模拟异步操作
    await Future.delayed(const Duration(seconds: 2));

    setState(() {
      _isLoading = false;
      _counter += 10;
      _counterHistory.add(_counter);
    });

    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('异步操作完成！计数器增加了10'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: _isDarkMode ? ThemeData.dark() : ThemeData.light(),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          title: Text(widget.title),
          actions: [
            IconButton(
              onPressed: _toggleTheme,
              icon: Icon(_isDarkMode ? Icons.light_mode : Icons.dark_mode),
              tooltip: '切换主题',
            ),
            IconButton(
              onPressed: _showHistoryDialog,
              icon: const Icon(Icons.history),
              tooltip: '查看历史',
            ),
          ],
        ),
        body:
            _isLoading
                ? const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CircularProgressIndicator(),
                      SizedBox(height: 16),
                      Text('正在处理...'),
                    ],
                  ),
                )
                : SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    children: [
                      // 计数器显示区域
                      Card(
                        child: Padding(
                          padding: const EdgeInsets.all(20),
                          child: Column(
                            children: [
                              const Text(
                                '当前计数',
                                style: TextStyle(fontSize: 18),
                              ),
                              const SizedBox(height: 10),
                              Text(
                                '$_counter',
                                style:
                                    Theme.of(context).textTheme.headlineLarge,
                              ),
                              const SizedBox(height: 20),
                              // 进度条显示
                              LinearProgressIndicator(
                                value: _counter / 100,
                                backgroundColor: Colors.grey[300],
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  _counter >= 100 ? Colors.red : Colors.blue,
                                ),
                              ),
                              const SizedBox(height: 10),
                              Text(
                                '进度: ${(_counter / 100 * 100).clamp(0, 100).toInt()}%',
                                style: const TextStyle(fontSize: 12),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),

                      // 基础按钮组件
                      Card(
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              const Text(
                                '基础操作',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Expanded(
                                    child: ElevatedButton.icon(
                                      onPressed: _decrementCounter,
                                      icon: const Icon(Icons.remove),
                                      label: const Text('减少'),
                                    ),
                                  ),
                                  const SizedBox(width: 8),
                                  Expanded(
                                    child: ElevatedButton.icon(
                                      onPressed: _incrementCounter,
                                      icon: const Icon(Icons.add),
                                      label: const Text('增加'),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 8),
                              OutlinedButton(
                                onPressed: _resetCounter,
                                child: const Text('重置计数器'),
                              ),
                              const SizedBox(height: 8),
                              TextButton(
                                onPressed: _showCustomValueDialog,
                                child: const Text('设置自定义值'),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),

                      // 功能型组件
                      Card(
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              const Text(
                                '高级功能',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 16),
                              ElevatedButton.icon(
                                onPressed: _simulateAsyncOperation,
                                icon: const Icon(Icons.sync),
                                label: const Text('异步操作 (+10)'),
                              ),
                              const SizedBox(height: 8),
                              SwitchListTile(
                                title: const Text('启用动画效果'),
                                subtitle: const Text('切换按钮动画'),
                                value: _counter % 2 == 0,
                                onChanged: (value) {
                                  // 这里可以添加动画开关逻辑
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),

                      // 可滚动组件 - 最近历史
                      Card(
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                '最近操作历史',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 16),
                              SizedBox(
                                height: 200,
                                child:
                                    _counterHistory.isEmpty
                                        ? const Center(child: Text('暂无操作历史'))
                                        : ListView.builder(
                                          itemCount:
                                              _counterHistory.length > 10
                                                  ? 10
                                                  : _counterHistory.length,
                                          itemBuilder: (context, index) {
                                            final reversedIndex =
                                                _counterHistory.length -
                                                1 -
                                                index;
                                            return ListTile(
                                              leading: CircleAvatar(
                                                backgroundColor:
                                                    Colors.blue[100],
                                                child: Text(
                                                  '${reversedIndex + 1}',
                                                ),
                                              ),
                                              title: Text(
                                                '计数: ${_counterHistory[reversedIndex]}',
                                              ),
                                              subtitle: Text(
                                                '操作时间: ${DateTime.now().toString().substring(11, 19)}',
                                              ),
                                              trailing: Icon(
                                                _counterHistory[reversedIndex] >
                                                        _counterHistory[reversedIndex -
                                                            1]
                                                    ? Icons.trending_up
                                                    : Icons.trending_down,
                                                color:
                                                    _counterHistory[reversedIndex] >
                                                            _counterHistory[reversedIndex -
                                                                1]
                                                        ? Colors.green
                                                        : Colors.red,
                                              ),
                                            );
                                          },
                                        ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
        floatingActionButton: FloatingActionButton.extended(
          onPressed: _incrementCounter,
          tooltip: '增加计数',
          icon: const Icon(Icons.add),
          label: const Text('计数'),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _customValueController.dispose();
    super.dispose();
  }
}
